package com.crazy.mybatis.gerenator.service.xml;

import java.util.List;

import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Component;

import com.crazy.mybatis.gerenator.service.Context;
import com.crazy.mybatis.gerenator.service.common.ElementName;

@Component
public class InsertBuilder extends AbstractElementBuilder implements ElementBuilder {

	private static final String DEFAULT_ID = "insert";

	public InsertBuilder() {
		this(DEFAULT_ID, ElementName.INSERT);
	}

	public InsertBuilder(String id, String elementName) {
		super(id, elementName);
	}

	@Override
	public Element build(Context context) {
		Element insert = DocumentHelper.createElement(this.elementName);
		insert.addAttribute("id", this.id);
		insert.addAttribute("parameterType", context.getAbsoluteModel());
		StringBuilder insertBuilder = new StringBuilder("INSERT INTO ").append(context.getTableName()).append(" (");
		StringBuilder valuesBuilder= new StringBuilder("VALUES").append("(");
		List<String> columnList = context.getColumnList();
		for (int i = 0; i < columnList.size(); i++) {
			String column = columnList.get(i);
			insertBuilder = insertBuilder.append(column).append(", ");
			valuesBuilder = valuesBuilder.append("#{").append(context.getColumnPropertyMap().get(column))
					.append(", jdbcType=").append(context.getColumnJdbcTypeMap().get(column))
					.append("}, ");
			if (i % 3 == 2) {
				insertBuilder = insertBuilder.append(intent(3));
				valuesBuilder = valuesBuilder.append(intent(3));
			}
		}
		insertBuilder = insertBuilder.deleteCharAt(insertBuilder.lastIndexOf(","));
		valuesBuilder = valuesBuilder.deleteCharAt(valuesBuilder.lastIndexOf(","));
		String insertStr = intent(2) + insertBuilder.toString().trim() + ")";
		String valuesStr = intent(2) + valuesBuilder.toString().trim() + ")";
		insert.setText(insertStr + valuesStr);
		
		return insert;
	}
	
}
